package com.dhcc.sds.busi.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.poi.excel.BigExcelWriter;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dhcc.cdc.busi.service.ICdcHospitalService;
import com.dhcc.cdc.busi.service.ICdcUserService;
import com.dhcc.cdc.sys.entity.ConfigurationEntity;
import com.dhcc.cdc.sys.service.IConfigurationService;
import com.dhcc.core.framework.base.controller.BaseController;
import com.dhcc.core.framework.security.ShiroKit;
import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.core.framework.util.RedisUtil;
import com.dhcc.core.framework.util.DateUtil;
import com.dhcc.core.modules.system.entity.User;
import com.dhcc.sds.base.service.ISdsCommonService;
import com.dhcc.sds.base.service.ISdsQcentityService;
import com.dhcc.sds.busi.service.ISdsOPQcincaseService;
import com.dhcc.sds.busi.vo.SdsOPQcincaseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 门诊上报管理
 *
 * @ClassName: SdsQcincaseController
 * @Description: TODO
 * @author sunyingjie
 * @date 2021-03-22 10:09:15
 */
@Controller
@RequestMapping("${sys.backendPath}/sds/sdsopqcincase")
public class SdsOPQcincaseController extends BaseController {

    private String PREFIX = "/backend/sds/sdsopqcincase/";

    @Autowired
    private ICdcHospitalService cdcHospitalService;
    @Autowired
    private ISdsCommonService sdsCommonService;
    @Autowired
    private ICdcUserService cdcUserService;
    @Autowired
    private ISdsQcentityService sdsQcentityService;
    @Autowired
    private ISdsOPQcincaseService sdsOPQcincaseService;
    @Autowired
    private RedisUtil redisUtil;


    /**
     * 跳转到单病种门诊上报管理首页
     */
    @RequestMapping("")
    public String index(@RequestParam Map<String, Object> params, Model model) {
        // 查询登录用户关联科室
        List<String> deptIds = sdsCommonService.getDeptIdsBySysUser();
        params.put("userLinkDepts", deptIds);
        //获取部门信息
        JSONArray officMap = cdcHospitalService.getOfficeMap();
        //加载用户关联科室
        JSONArray departMap = sdsCommonService.getDepartMap(new HashMap<>());
        //获取门诊管理病种
        JSONArray entityMap = sdsQcentityService.getEntityMapByConfig("SDS", "SDOPQCEntity");
        //管理医生
        JSONArray docMap = cdcUserService.getUserMap("1");
        //状态
        JSONArray statusMap = sdsCommonService.getDicCodeArray("SDQCMrStatus");
        //
        User user = ShiroKit.getUser();
        String execUser = user.getLoginName();
        model.addAttribute("officeMap",officMap);
        model.addAttribute("departMap",departMap);
        model.addAttribute("statusMap",statusMap);
        model.addAttribute("docMap",docMap);
        model.addAttribute("entityMap",entityMap);
        model.addAttribute("execUser",execUser);

        return PREFIX + "sdsopqcincase.html";
    }

    /**
     * @Description: 查询gridQCMrList页面数据
     * @Title: selectQCOPMrListByDate
     * @return: Object
     * @author: zhangdc
     * @date:2022-05-12 10:09:15
     */
    @RequestMapping("selectQCOPMrListByDate")
    @ResponseBody
    public Object selectQCOPMrListByDate(@RequestParam Map<String, Object> params) {
        List<String> deptIds = sdsCommonService.getDeptIdsBySysUser();
        params.put("userLinkDepts", deptIds);
        return sdsOPQcincaseService.selectQCOPMrListByDate(params);
    }

    /**
     * @Description: 查询入组/排除规则数据
     * @Title: selectRulesByQcEntityId
     * @return: Object
     * @author: zhangdc
     * @date:2022-05-16 10:09:15
     */
    @RequestMapping("selectRulesByQcEntityId")
    @ResponseBody
    public Object selectRulesByQcEntityId(@RequestParam Map<String, Object> params) {
        return sdsOPQcincaseService.selectRulesByQcEntityId(params);
    }

    /**
     * @Description: 查询门诊质控病种信息
     * @Title: selectQcEntityByLocId
     * @return: Object
     * @author: zhangdc
     * @date:2022-05-16 10:09:15
     */
    @RequestMapping("selectQcEntityByLocId")
    @ResponseBody
    public Object selectQcEntityByLocId(@RequestParam Long aLocOId) {
        return sdsOPQcincaseService.selectQcEntityByLocId(aLocOId);
    }

    /**
     * @Description: 门诊新入病种
     * @Title: inQcEntity
     * @return: Object
     * @author: zhangdc
     * @date:2022-05-16 10:09:15
     */
    @RequestMapping("inQcEntity")
    @ResponseBody
    public Object inQcEntity(@RequestParam Map<String, Object> params) {
        User user = ShiroKit.getUser();
            String execUser = user.getLoginName();
        params.put("execUser", execUser);
        return sdsOPQcincaseService.inQcEntity(params);
    }

    /**
     * @Description: 查询操作日志
     * @Title: selectOperLogByIncaseId
     * @return: Object
     * @author: zhangdc
     * @date:2022-05-18 10:09:15
     */
    @RequestMapping("selectOperLogByIncaseId")
    @ResponseBody
    public Object selectOperLogByIncaseId(@RequestParam String incaseId) {
        return sdsOPQcincaseService.selectOperLogByIncaseId(Long.parseLong(incaseId));
    }


    /**
     * @Description: 导出excel
     * @Title: export
     * @return: Object
     * @author: zhangdc
     * @date:2022-05-26 10:09:15
     */
    @RequestMapping("/export")
    public void export(HttpServletRequest request,
                       HttpServletResponse response){
        if (CommonUtil.isNotEmpty(redisUtil.get("gridQCMrList"))){
            // 通过工具类创建writer，默认创建xls格式
            BigExcelWriter writer = (BigExcelWriter) ExcelUtil.getBigWriter();
            // 重命名第一个Sheet的名称，不然会默认多出一个Sheet1的页
            writer.renameSheet("单病种表单");
            String res = redisUtil.get("gridQCMrList");
            DecimalFormat df = new DecimalFormat("0.00");
            List<SdsOPQcincaseVo> sdsOPQcincaseVoList = new ArrayList<>(JSONArray.parseArray(res, SdsOPQcincaseVo.class));
            // 一次性写出内容，使用默认样式
            if (CommonUtil.isNotEmpty(sdsOPQcincaseVoList)){
                ArrayList<Map<String, Object>> rows = CollUtil.newArrayList();
                for (SdsOPQcincaseVo sdsOPQcincaseVo : sdsOPQcincaseVoList){
                    Map<String, Object> row = new LinkedHashMap<>();
                    row.put("单病种", sdsOPQcincaseVo.getQcEntityDesc());
                    row.put("患者姓名", sdsOPQcincaseVo.getName());
                    row.put("登记号", sdsOPQcincaseVo.getRegistNum());
                    String ratio;
                    if (Objects.equals(0, sdsOPQcincaseVo.geteCount()) && Objects.equals(0, sdsOPQcincaseVo.getnCount())){
                        ratio = "0%";
                    }else {
                        ratio = df.format((float) sdsOPQcincaseVo.geteCount() / (sdsOPQcincaseVo.geteCount() + sdsOPQcincaseVo.getnCount()) * 100);
                        ratio += "%";
                    }
                    row.put("表单填报率", ratio);
                    row.put("表单状态", sdsOPQcincaseVo.getQcCurrStatusDesc());
                    row.put("管床医生", sdsOPQcincaseVo.getAdmDoctorName());
                    row.put("就诊日期", DateUtil.getDay(sdsOPQcincaseVo.getAdmDate()));
                    row.put("入单日期", DateUtil.getDay(sdsOPQcincaseVo.getQcInDate()));
                    sdsOPQcincaseVo.getQcCurrStatus();
                    String upStatus;
                    if (Objects.equals("Up", sdsOPQcincaseVo.getQcCurrStatus())){
                        upStatus = "已上传";
                    }else if (Objects.equals("Check", sdsOPQcincaseVo.getQcCurrStatus()) || Objects.equals("tUp", sdsOPQcincaseVo.getQcCurrStatus())){
                        upStatus = "待上传";
                    }else {
                        upStatus = "待填报";
                    }
                    row.put("上传接口平台", upStatus);
                    rows.add(row);
                }
                writer.write(rows);
                writer.setColumnWidth(0, 20);
                writer.setColumnWidth(1, 20);
                writer.setColumnWidth(2, 20);
                writer.setColumnWidth(6, 20);
                writer.setColumnWidth(7, 20);
            }else {
                List<String> row = CollUtil.newArrayList("无数据");
                List<List<String>> rows = new ArrayList<List<String>>();
                rows.add(row);
                writer.write(rows);
            }

            ServletOutputStream out = null;
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                String fileName = "单病种表单" + sdf.format(new Date()) + ".xlsx";
                response.setContentType("application/vnd.ms-excel;charset=utf-8");
                response.setHeader("Content-Disposition",
                        "attachment;filename=" + new String(fileName.getBytes("GBK"), "ISO8859_1"));
                out = response.getOutputStream();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                writer.flush(out);
                // 关闭writer，释放内存
                writer.close();
            }
        }
    }

}
